package com.boot2.core.web.controller;

import com.boot2.core.cache.redis.RedisDao;
import com.boot2.core.constant.CoreConstant;
import com.boot2.core.dict.ErrorCode;
import com.boot2.core.model.vo.Result;
import com.boot2.core.utils.Base64StringUtil;
import com.boot2.core.utils.ResultBuilder;
import com.boot2.core.utils.SnowflakeIdFactory;
import com.boot2.core.utils.VerifyCodeUtils;
import com.google.common.collect.ImmutableMap;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;

import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.Serializable;
import java.util.Map;

/**
 * 验证码操作处理
 *
 * @author ruoyi
 */
@Api(tags = "验证码")
@RestController
public class CaptchaController {

    @Autowired(required = false)
    RedisDao redisDao;

    /**
     * 生成验证码
     */
    @ApiOperation(value = "生成验证码")
    @GetMapping("/captchaImage")
    public Result<Map<String, Serializable>> getCode() throws IOException {
        // 生成随机字串
        String verifyCode = VerifyCodeUtils.generateVerifyCode(4);
        // 唯一标识
        String uuid = String.valueOf(SnowflakeIdFactory.generateId());
        String verifyKey = CoreConstant.CAPTCHA_CODE_KEY + uuid;

        redisDao.setForMinutes(verifyKey, verifyCode, 20L);
        // 生成图片
        int w = 111, h = 36;
        ByteArrayOutputStream stream = new ByteArrayOutputStream();
        VerifyCodeUtils.outputImage(w, h, stream, verifyCode);
        try {
            Result<Map<String, Serializable>> result = ResultBuilder.buildResult(ImmutableMap.of("uuid", uuid, "img", Base64StringUtil.getBase64(stream.toByteArray())));
            return result;
        } catch (Exception e) {
            e.printStackTrace();
            return ResultBuilder.buildResult(ErrorCode.code_500, "验证码生成失败");
        } finally {
            stream.close();
        }
    }
}
